package com.info33.platform.doc.service.impl;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.info33.platform.common.mvc.vo.Result;
import com.info33.platform.doc.dao.DocFileDao;
import com.info33.platform.doc.dao.DocFileUserDao;
import com.info33.platform.doc.dto.DocFileUserSaveDTO;
import com.info33.platform.doc.entity.DocFile;
import com.info33.platform.doc.entity.DocFileUser;
import com.info33.platform.doc.service.DocFileUserService;
import com.info33.platform.doc.vo.DocFileUserVO;

/**
 * @author admin
 */
@Service
public class DocFileUserServiceImpl extends ServiceImpl<DocFileUserDao, DocFileUser> implements DocFileUserService {

    @Autowired
    private DocFileUserDao docFileUserDao;
    @Autowired
    private DocFileDao docFileDao;

	@Override
	@Transactional(rollbackFor = {Exception.class, Error.class})
	public Result<?> saveFileUser(DocFileUserSaveDTO docFileUserSaveDTO) {
		DocFile docFile = docFileDao.selectById(docFileUserSaveDTO.getFileId());
		if(ObjectUtils.isEmpty(docFile)) {
			return Result.error("此条文档不存在");
		}
		//先删除之前权限，保留文档创建者默认权限，再进行新增
		docFileUserDao.delete(new QueryWrapper<DocFileUser>().eq("file_id", docFile.getId()).ne("IFNULL(user_id,'')", docFile.getCreateBy()));
		List<DocFileUser> fileUserList = docFileUserSaveDTO.getDocFileUserList();
		if(CollectionUtils.isEmpty(fileUserList)) {
			return Result.ok();
		}
		for(DocFileUser docFileUser : fileUserList) {
			docFileUser.setFileId(docFile.getId());
		}
		return this.saveBatch(fileUserList) ? Result.ok() : Result.error();
	}

	@Override
	public Result<Map<Integer, List<DocFileUserVO>>> getFileUserDetail(Long fileId) {
		DocFile docFile = docFileDao.selectById(fileId);
		if(ObjectUtils.isEmpty(docFile)) {
			return Result.error("此条文档不存在");
		}
		Map<Integer, List<DocFileUserVO>> map = new HashMap<Integer, List<DocFileUserVO>>();
		for(int i = 1; i <= 5; i++) {
			List<DocFileUserVO> docFileUserVOList = docFileUserDao.getFileUserDetail(fileId, docFile.getCreateBy(), i);
			map.put(i, docFileUserVOList);
		}
		
		return Result.ok(map);
	}

}